import { defineStore } from 'pinia'

export const useOrderStore = defineStore('order', {
  state: () => ({
    storeInfo: null,
    orderInfo: null,
    cartItems: [],
    selectedAddress: null,
    selectedCoupon: null,
    orderRemark: '',
    utensilsCount: 2,
    deliveryFee: 5,
    packagingFee: 2
  }),
  
  getters: {
    totalAmount: (state) => {
      return state.cartItems.reduce((total, item) => {
        return total + (item.price * item.quantity)
      }, 0)
    },
    
    finalAmount: (state) => {
      let amount = state.cartItems.reduce((total, item) => {
        return total + (item.price * item.quantity)
      }, 0)
      
      // 添加配送费和打包费
      if (state.orderInfo?.mode === 'takeout') {
        amount += state.deliveryFee
      }
      amount += state.packagingFee
      // 减去优惠券金额
      if (state.selectedCoupon) {
        amount -= state.selectedCoupon.amount
      }
      
      return amount.toFixed(2)
    }
  },
  
  actions: {
    setOrderData(data) {
      this.storeInfo = data.storeInfo
      this.orderInfo = data.orderInfo
      this.cartItems = data.cartItems
    },
    
    setSelectedAddress(address) {
      this.selectedAddress = address
    },
    
    setSelectedCoupon(coupon) {
      this.selectedCoupon = coupon
    },
    
    setOrderRemark(remark) {
      this.orderRemark = remark
    },
    
    setUtensilsCount(count) {
      this.utensilsCount = count
    },
    
    clearOrderData() {
      this.storeInfo = null
      this.orderInfo = null
      this.cartItems = []
      this.selectedAddress = null
      this.selectedCoupon = null
      this.orderRemark = ''
      this.utensilsCount = 2
    }
  }
}) 